package com.robert.recycleviewdemo

import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView


class MainActivity : AppCompatActivity() {
    lateinit var rv: RecyclerView
    lateinit var h: EditText
    lateinit var v: EditText
    lateinit var l: EditText
    lateinit var t: EditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rv = findViewById(R.id.rv)
        rv.layoutManager = GridLayoutManager(this, 2)
        rv.adapter = ItemAdapter(this)
//        rv.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.HORIZONTAL))
        h = findViewById(R.id.h)
        v = findViewById(R.id.v)
        l = findViewById(R.id.l)
        t = findViewById(R.id.t)

    }

    fun layout(view: View) {
        rv.removeAllViews()
        val hvPercent = h.text.toString().trim() + ":" + v.text.toString().trim()
        val ltPercent = l.text.toString().trim() + ":" + t.text.toString().trim()
        val itemAdapter = ItemAdapter(this, hvPercent, ltPercent)
        rv.adapter = itemAdapter

//        rv.addItemDecoration(com.robert.recycleviewdemo.ItemDecoration(this, R.drawable.divider_black))
    }

    class ItemAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private val context: Context
        private val widthPixels: Int
        private val hvPercent: String
        private val ltPercent: String
        private val width: Int
        private val hv: List<String>
        private val height: Double
        private val lt: List<String>
        private val itemMarginLeft: Double
        private val itemMarginTop: Double


        constructor(context: Context) : this(context, "14:6", "0.1:0.8")

        constructor(context: Context, hvPercent: String, ltPercent: String) {
            this.context = context
            widthPixels = context.resources.displayMetrics.widthPixels
            this.hvPercent = hvPercent
            this.ltPercent = ltPercent
            width = (widthPixels - DensityUtils.dp2px(context, 6f) * 3) / 2
            hv = hvPercent.split(":")
            height = width / hv[0].toDouble() * hv[1].toDouble();
            lt = ltPercent.split(":")
            itemMarginLeft = width * lt[0].toDouble()
            itemMarginTop = height * lt[1].toDouble()
        }


        override fun getItemCount(): Int {
            return 10
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val txt: TextView = holder.itemView.findViewById(R.id.pos)
            txt.text = position.toString()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.item, parent, false)
            view.layoutParams.width = width
            view.layoutParams.height = height.toInt()
            val layoutParams: RelativeLayout.LayoutParams = view.findViewById<View>(R.id.pos).layoutParams as RelativeLayout.LayoutParams
            layoutParams.leftMargin = itemMarginLeft.toInt()
            layoutParams.topMargin = itemMarginTop.toInt()
            return object : RecyclerView.ViewHolder(view) {}
        }

    }

    class ItemDecoration : RecyclerView.ItemDecoration() {

        private fun getSpanCount(parent: RecyclerView): Int {
            // 列数
            var spanCount = -1
            val layoutManager = parent.layoutManager
            if (layoutManager is GridLayoutManager) {
                spanCount = layoutManager.spanCount
            } else if (layoutManager is StaggeredGridLayoutManager) {
                spanCount = layoutManager.spanCount
            } else if (layoutManager is LinearLayoutManager) {
                spanCount = 1
            }
            return spanCount
        }

        private fun isLastRaw(parent: RecyclerView, pos: Int, spanCount: Int): Boolean {
            val layoutManager = parent.layoutManager
            var childCount = parent.adapter.itemCount
            if (layoutManager is GridLayoutManager) {
                childCount -= childCount % spanCount
                if (pos >= childCount)//
                    return true
            } else if (layoutManager is StaggeredGridLayoutManager) {
                val orientation = layoutManager.orientation
                // StaggeredGridLayoutManager 且纵向滚动
                if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                    childCount = childCount - childCount % spanCount
                    // 如果是最后一行，则不需要绘制底部
                    if (pos >= childCount)
                        return true
                } else {// StaggeredGridLayoutManager 且横向滚动
                    // 如果是最后一行，则不需要绘制底部
                    if ((pos + 1) % spanCount == 0) {
                        return true
                    }
                }
            } else if (layoutManager is LinearLayoutManager) {
                if (childCount - 1 == pos) {
                    return true
                }
            }
            return false
        }

        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            val isLast = isLastRaw(parent, (view.layoutParams as RecyclerView.LayoutParams).viewLayoutPosition, getSpanCount(parent))
            if (isLast) {
                outRect.bottom = DensityUtils.dp2px(view.context, 40f)
            }
        }
    }

}
